<?php

namespace App\Admin\Controllers;

use Carbon\Carbon;
use App\Models\Order;
use Encore\Admin\Grid;
use App\Models\Vendor;
use App\Imports\OrderImport;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Supports\Delivery\Express;
use Illuminate\Support\Facades\DB;
use App\Events\OrderDeliveredEvent;
use Maatwebsite\Excel\Facades\Excel;
use App\Admin\Actions\OrderAction\OrderCancel;
use Illuminate\Database\Eloquent\Builder;
use App\Admin\Tools\VendorOrderExportTool;
use App\Admin\Tools\VendorOrderImportTool;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Foundation\Validation\ValidatesRequests;

class VendorOrdersController extends AdminController
{
	use ValidatesRequests;
	
    protected $title = '商户订单管理';
    
    protected function grid()
    {
        $grid = new Grid(new Order());
        $this->gridVendor($grid);
	    
	    $grid->column('id', 'ID')->width(50);
	    $grid->column('user_id', '会员')->display(function () {
	    	return $this->user->nameText();
	    });
	    $grid->column('type', '类型')->display(function ($type) {
		    return config("site.order.types.$type");
	    });
	    $grid->column('number', '订单号');
	    $grid->column('created_at', '创建时间')->display(function () {
		    return (string)$this->created_at;
	    });
	    $grid->column('paid_at', '付款时间')->display(function () {
		    return $this->paid_at ? (string)$this->paid_at : '待付款...';
	    });
	    $grid->column('paid_method', '付款方式')->display(function ($value) {
		    if (empty($value)) {return "<i class='fa fa-times-circle text-danger'></i> 未支付";}
		    $method = config("site.payment.methods.{$value}");
		    $method = empty($method) ? $value : $method;
		    $text = "<i class='fa fa-check-circle text-success'></i> {$method}";
		    return $text;
	    });
	    $grid->column('total_amount', '金额');
	    $grid->column('delivery_status', '物流状态')->display(function ($value) {
		    if ($value === 'pending') {return _label('待发货', 'default');}
		    if ($value === 'delivered') {return _label('已发货', 'info');}
		    if ($value === 'received') {return _label('已收货', 'primary');}
	    });
	    $grid->column('is_closed', '关闭状态')->display(function ($value) {
		    return $value ? _label('超时关闭', 'default') : _label('状态正常', 'success');
	    });
	    $grid->column('cancelled_at', '取消状态')->display(function ($value) {
		    return empty($value) ? _label('状态正常', 'success') : _label('已经取消', 'danger');
	    });
	    
	    $this->gridTools($grid);
	    $grid->disableRowSelector();
	    $grid->disableCreateButton();
	    $grid->disableExport();
	    $this->gridActions($grid);

        return $grid;
    }
    
    protected function gridVendor(Grid $grid)
    {
	    $vendor = Vendor::query()->where('phone', Admin::user()->username)->first();
	    if ($vendor) {
		    $grid->model()->whereHas('items', function (Builder $builder) use ($vendor) {
			    $builder->where('vendor_id', $vendor->id);
		    })->orderByDesc('id');
	    } else {
		    $grid->model()->where('id', 0);
	    }
    }
    
    protected function gridTools(Grid $grid)
    {
    	$grid->tools(function (Grid\Tools $tools) {
		    $tools->append(new VendorOrderExportTool());
		    $tools->append(new VendorOrderImportTool());
	    });
    }
    
    protected function gridActions(Grid $grid)
    {
    	$grid->actions(function (Grid\Displayers\Actions $actions) {
    		$actions->disableEdit();
    		$actions->disableDelete();
    		$actions->add(new OrderCancel());
	    });
    }
    
    public function show($id, Content $content)
    {
	    $order = Order::findOrFail($id);
	    $express = app(Express::class)->track($order);
	    return $content->header('订单明细')
		    ->body(view('admin.orders.show', [
			    'order' => $order, 'express' => $express,
		    ]));
    }
    
    public function import()
    {
	    if (!$file = request()->file('orders')) {
		    admin_toastr('请选择文件', 'error');
		    return redirect()->back();
	    }
	
	    ini_set('memory_limit', '3072M'); // temporarily.
	    Excel::import(new OrderImport(), request()->file('orders'));
	    admin_toastr('批量发货成功', 'success');
	    return redirect()->back();
    }
    
    public function deliver(Order $order)
    {
	    if (!$order->isPaid()) {
		    admin_error('title', '当前订单未支付');
		    return redirect()->back();
	    }
	    if ($order->delivery_status !== 'pending') {
		    admin_error('title', '当前订单已发货');
		    return redirect()->back();
	    }
	
	    $data = $this->validate(request(), [
		    'delivery_company' => 'required',
		    'delivery_number' => 'required',
	    ], [], [
		    'delivery_company' => '物流公司',
		    'delivery_number' => '物流单号',
	    ]);
	
	    $data['delivery_time'] = Carbon::now()->toDateTimeString();
	
	    DB::transaction(function () use ($order, $data) {
		    $order->items()->update([
			    'delivery_status' => 'delivered',
			    'delivery_data' => $data,
		    ]);
		
		    $order->update([
			    'delivery_status' => 'delivered',
			    'delivery_data' => $data,
		    ]);
	    });
	
	    event(new OrderDeliveredEvent($order));
	
	    admin_toastr('发货成功', 'success');
	
	    return redirect()->back();
    }
}
